package sugar

import (
	"crypto/md5"
	"crypto/rand"
	"encoding/hex"
	"log"
)

// md5Hash generates an MD5 hash of a given input
func md5Hash(input string) string {
	hash := md5.Sum([]byte(input))
	return hex.EncodeToString(hash[:])
}

// HashPassword hashes the password with salt using double MD5
func HashPassword(password, salt string) string {
	// First MD5 hash of the password
	firstHash := md5Hash(password)
	// Concatenate the first hash with the salt and hash again
	finalHash := md5Hash(firstHash + salt)
	return finalHash
}

// GenerateSalt generates a 6-character random salt
func GenerateSalt(length int) string {
	const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
	salt := make([]byte, length)
	_, err := rand.Read(salt)
	if err != nil {
		log.Print(err)
		return ""
	}
	for i, b := range salt {
		salt[i] = charset[b%byte(len(charset))]
	}
	return string(salt)
}
